package com.anywhere.freightman.app.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.anywhere.freightman.app.controller.request.LoginRequest;
import com.anywhere.freightman.car.model.DriverModel;
import com.anywhere.freightman.car.service.IDriverService;
import com.anywhere.freightman.client.WxService;
import com.anywhere.freightman.common.entity.ReturnResp;
import com.anywhere.freightman.common.entity.car.DriverEntity;
import com.anywhere.freightman.common.enumeration.TokenType;
import com.anywhere.freightman.common.ex.CustomException;
import com.anywhere.freightman.system.model.AccessToken;
import com.anywhere.freightman.system.service.IAccessTokenService;
import com.google.common.base.Strings;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("wx")
@Api("微信相关接口")
public class WxController {

    @Value("${wx.app.id}")
    private String wxAppId;
    @Value("${wx.app.secret}")
    private String wxSecret;

    @Autowired
    private WxService wxService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private IAccessTokenService accessTokenService;

    @PostMapping("login")
    @ApiOperation("小程序登录")
    public ReturnResp login(@RequestBody LoginRequest requestEntity) {
        DriverEntity entity = driverService.login(requestEntity.getUsername(), requestEntity.getPassword());
        if (entity == null) {
            throw new CustomException("账号或密码错误");
        }
        String openId = getOpenId(requestEntity.getCode());
        DriverModel model = driverService.getById(entity.getId());
        driverService.cleanWxOpenId(openId);
        model.setWxAppId(openId);
        driverService.update(model);
        return ReturnResp.buildOk(entity);
    }

    @PostMapping("jscode2session")
    @ApiOperation("登录凭证校验")
    public ReturnResp jscode2session(@RequestParam("code") String code) {
        String openId = getOpenId(code);
//        String sessionKey = jsonObject.getString("session_key");
        DriverModel model = driverService.selectByWxAppId(openId);
        if (model == null) {
            return ReturnResp.buildFail("用户还未登陆");
        }
        DriverEntity entity = new DriverEntity();
        BeanUtils.copyProperties(model, entity);

        AccessToken token = accessTokenService.insert(entity.getId(), TokenType.DRIVER);
        entity.setToken(token.getToken());

        return ReturnResp.buildOk(entity);
    }

    private String getOpenId(String code) {
        String json = wxService.jscode2session(wxAppId, wxSecret, code, "authorization_code");
        JSONObject jsonObject = JSON.parseObject(json);
        String errCode = jsonObject.getString("errcode");
        if (!Strings.isNullOrEmpty(errCode)) {
            throw new CustomException(jsonObject.getString("errmsg"));
        }
        return jsonObject.getString("openid");
    }


}
